package com.minyon_web_admin.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.minyon_utils.StringUtil;
import com.minyon_web_admin.common.base.BaseController;
import com.minyon_web_admin.model.SysUserBean;
import com.minyon_web_admin.service.PasswordHelper;

@Controller
public class LoginController extends BaseController {
 
	/**
	 * 用户登录
	 * 
	 * @param user
	 *            　登录用户
	 * @return
	 */
	@RequestMapping(value = "/login.shtml", method = RequestMethod.POST)
	public String login(String userName, String password,
			HttpSession session,Model model) {
		minYonlogger.info("登录请求处理开始!");
		ModelAndView modelView = new ModelAndView();
		// 获取 subject
		Subject currentUser = SecurityUtils.getSubject();
		SysUserBean user = new SysUserBean();
		/*user.setLoginName(userName);
		user.setPassword(password);
		pwdHelp.encryptPassword(user);*/
		// 创建用户名/密码身份验证Token
		UsernamePasswordToken token = new UsernamePasswordToken(userName,
				password);
		 token.setRememberMe(true);
		 try {
			// 登录 即验证身份-->securityManager.login()->Authenticator-->realm
			currentUser.login(token);
			
			minYonlogger.info("登录成功!");
			user.setLoginName(userName);
			session.setAttribute("userinfo", user);
			return "redirect:/index.shtml";
		} catch (UnknownAccountException e) {// 身份验证失败
			minYonlogger.info("用户名/密码错误");
			model.addAttribute("message", "用户名/密码错误");
			return "/login";

		} catch (IncorrectCredentialsException e) {
			minYonlogger.info("密码错误");
			model.addAttribute("message", "密码错误");
			return "/login";
		} catch (AuthenticationException e) {
			// 其他错误，比如锁定，如果想单独处理请单独 catch 处理
			minYonlogger.info("其他错误：" + e.getMessage());
			model.addAttribute("message", "login errors");
			return "/login";
		}
		 
	}
}
